<script setup>
import { appStore } from '@/sotre/modules/app';
import { upload } from '@/api/index';
import { getEnterpriseList } from '@/utils/request';

const { userInfo, enterpriseList, power } = toRefs(appStore());
const $post = inject('$post');
const $put = inject('$put');

const enterpriseValue = ref(userInfo.value.currEnterpriseByCache.id);
const show = ref(false);
const changePhone = reactive({
    oldPhone: userInfo.value.phone,
    oldCode: '',
    newPhone: '',
    newCode: '',
});
const codeTime1 = ref(0);
let codeTimer1 = null;

const codeTime2 = ref(0);
let codeTimer2 = null;

getEnterpriseList();

function uploadFun() {
    uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: async res => {
            const r = await upload(res);
            if (r && r.url) {
                userInfo.value.avatar = r.url;
            }
        },
    });
}

function logout() {
    uni.showModal({
        title: '提示',
        content: '确定退出登录吗？',
        success: res => {
            if (res.confirm) {
                uni.removeStorageSync('TOKEN');
                uni.reLaunch({
                    url: '/pages/index/index',
                });
            }
        },
    });
}

function save() {
    if (!userInfo.value.name) {
        uni.showToast({
            title: '请输入昵称',
            icon: 'none',
        });
        return;
    }
    uni.showLoading({
        title: '保存中...',
        mask: true,
    });
    $post('/platform/users/Mobileupdate', userInfo.value).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
            uni.showToast({
                title: '保存成功',
                icon: 'success',
            });
            uni.setStorageSync('userInfo', userInfo.value);
            uni.navigateBack();
        }
    });
}

function changePhoneFun() {
    if (!changePhone.newPhone) {
        uni.showToast({
            title: '请输入新手机号',
            icon: 'none',
        });
        return;
    }
    if (!changePhone.newCode || !changePhone.oldCode) {
        uni.showToast({
            title: '请输入验证码',
            icon: 'none',
        });
        return;
    }
    uni.showLoading({
        title: '保存中...',
        mask: true,
    });
    $put('/platform/users/changePhone', changePhone).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
            uni.showToast({
                title: '保存成功',
                icon: 'success',
            });
            show.value = false;
            userInfo.value.phone = changePhone.newPhone;
            uni.setStorageSync('userInfo', userInfo.value);
        }
    });
}

function getCode1() {
    if (codeTime1.value > 0) return;
    if (!changePhone.oldPhone || changePhone.oldPhone.length !== 11) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
        });
        return;
    }
    $post('/auth/platform/smsSend', {
        phone: changePhone.oldPhone,
    }).then(res => {
        if (res.code === 200) {
            uni.showToast({
                title: '验证码已发送',
                icon: 'success',
            });
            codeTime1.value = 60;
            codeTimer1 = setInterval(() => {
                codeTime1.value--;
                if (codeTime1.value <= 0) {
                    clearInterval(codeTimer1);
                    codeTimer1 = null;
                }
            }, 1000);
        }
    });
}

function getCode2() {
    if (codeTime2.value > 0) return;
    if (!changePhone.newPhone || changePhone.newPhone.length !== 11) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
        });
        return;
    }
    $post('/auth/platform/smsSend', {
        phone: changePhone.newPhone,
    }).then(res => {
        if (res.code === 200) {
            uni.showToast({
                title: '验证码已发送',
                icon: 'success',
            });
            codeTime2.value = 60;
            codeTimer2 = setInterval(() => {
                codeTime2.value--;
                if (codeTime2.value <= 0) {
                    clearInterval(codeTimer2);
                    codeTimer2 = null;
                }
            }, 1000);
        }
    });
}

function handleConfirm(e) {
    if (e.value === userInfo.value.currEnterpriseByCache.id) return;
    uni.showModal({
        title: '提示',
        content: '确定切换团队吗？',
        success: async res => {
            if (res.confirm) {
                try {
                    const r = await $put('/platform/users/enterprise?enterpriseId=' + e.value);
                    if (r?.code === 200) {
                        $post('/platform/users/getUserInfo').then(res => {
                            userInfo.value = res.data.platformUsers;
                            power.value = res.data.permissions.map(item => item.split(':')[2]);
                            localStorage.setItem(
                                'X-Enterprise-ID',
                                res.data.platformUsers.lastEnterpriseId
                            );
                        });
                    }
                    uni.showToast({ title: '团队已切换', icon: 'success' });
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages/home/index',
                        });
                    }, 1000);
                } catch (e) {
                    uni.showToast({ title: '切换失败，请稍后再试', icon: 'none' });
                }
            } else {
                enterpriseValue.value = [userInfo.value.currEnterpriseByCache.id];
            }
        },
    });
}
</script>

<template>
    <div class="set">
        <u-navbar title="设置" placeholder autoBack></u-navbar>
        <wd-cell-group border>
            <wd-cell title="用户头像" center>
                <div class="upload" @click="uploadFun">
                    <image v-if="userInfo.avatar" :src="userInfo.avatar" mode="aspectFill"></image>
                    <div class="empty" v-else>
                        <wd-icon name="photo" size="22px"></wd-icon>
                    </div>
                </div>
            </wd-cell>
            <wd-input
                v-model="userInfo.name"
                label="账户昵称"
                placeholder="请输入姓名"
                cell
                clearable
            ></wd-input>
            <wd-cell title="手机号码">
                <div class="phone">
                    <span style="flex: 1">{{ userInfo.phone }}</span>
                    <wd-button type="warning" size="small" @click="show = true">
                        修改手机号
                    </wd-button>
                </div>
            </wd-cell>
            <wd-cell title="用户性别" center>
                <wd-radio-group
                    v-model="userInfo.sex"
                    inline
                    cell
                    label="性别"
                    shape="dot"
                    checked-color="#f0883a"
                >
                    <wd-radio :value="1">男</wd-radio>
                    <wd-radio :value="2">女</wd-radio>
                </wd-radio-group>
            </wd-cell>
            <wd-picker
                :columns="enterpriseList"
                label="切换团队"
                v-model="enterpriseValue"
                value-key="id"
                label-key="name"
                @confirm="handleConfirm"
            />
        </wd-cell-group>
        <div class="btn">
            <u-button type="warning" @click="save">保存信息</u-button>
            <u-button type="error" @click="logout">退出登录</u-button>
        </div>
        <wd-popup v-model="show" custom-style="border-radius:32rpx;">
            <div class="change">
                <div class="title">修改手机号</div>
                <wd-cell-group>
                    <wd-input label="原手机号" v-model="changePhone.oldPhone" disabled></wd-input>
                    <wd-cell title="验证码">
                        <div class="phone">
                            <div class="input">
                                <input
                                    type="number"
                                    v-model="changePhone.oldCode"
                                    placeholder="请输入验证码"
                                    :maxlength="6"
                                />
                            </div>
                            <wd-button type="warning" size="small" @click="getCode1">
                                {{ codeTime1 > 0 ? codeTime1 + 's' : '发送验证码' }}
                            </wd-button>
                        </div>
                    </wd-cell>
                    <wd-input
                        label="新手机号"
                        v-model="changePhone.newPhone"
                        :maxlength="11"
                        placeholder="请输入新手机号"
                        clearable
                    ></wd-input>
                    <wd-cell title="验证码">
                        <div class="phone">
                            <div class="input">
                                <input
                                    type="number"
                                    v-model="changePhone.newCode"
                                    placeholder="请输入验证码"
                                    :maxlength="6"
                                />
                            </div>
                            <wd-button type="warning" size="small" @click="getCode2">
                                {{ codeTime2 > 0 ? codeTime2 + 's' : '发送验证码' }}
                            </wd-button>
                        </div>
                    </wd-cell>
                </wd-cell-group>
                <div class="btns">
                    <u-button @click="show = false">取消</u-button>
                    <u-button type="error" @click="changePhoneFun">保存</u-button>
                </div>
            </div>
        </wd-popup>
    </div>
</template>

<style lang="scss" scoped>
.set {
    .btn {
        margin-top: 30px;
        padding: 0 20px;
        display: flex;
        flex-direction: column;
        gap: 15px;
    }
    :deep(.wd-cell-group) {
        padding: 15px 12px;
        .wd-cell__left,
        .wd-input__label,
        .wd-picker__label {
            width: 80px;
            flex: none;
            color: #333;
            font-weight: bold;
        }
        .wd-picker__value {
            text-align: right;
        }

        .phone {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            text-align: left;
        }
        .upload {
            display: flex;
            justify-content: flex-end;

            image {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                background: #edf2fa;
            }
            .empty {
                background: #edf2fa;
                width: 60px;
                height: 60px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
    }
    .change {
        padding: 15px;
        border-radius: 32rpx;
        background: #fff;
        width: 80vw;
        :deep(.wd-cell-group) {
            padding: 10px 5px !important;
            .wd-cell__left,
            .wd-input__label {
                width: 60px;
                flex: none;
                color: #333;
                font-weight: normal;
            }
            .input {
                padding: 3px 10px;
                border-bottom: 1px solid #e5e5e5;
                flex: 1;
                margin-right: 15px;
            }
            input {
                font-size: 14px;
            }
            .wd-input__inner {
                padding-left: 10px;
                border-bottom: 1px solid #e5e5e5;
                padding-bottom: 3px;
            }
        }
        .btns {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
    }
}
</style>
